<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <div>
            <input type="text" v-model="inpVal">
            <button @click="addTodoFunc">添加todos</button>
            <button @click="addTodoAsyncFunc">异步添加todos</button>
        </div>
        <div>
            <h1>todos列表</h1>
            <div :key="item.id" v-for="(item,index) in this.$store.state.todos">
                {{item.text}}
                <button @click="deleteTodo(index)">删除</button>
            </div>
        </div>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vuex/dist/vuex.js"></script>
<script>
    //代码优化
    // a,把操作变成常量
    //addTodo => ADD_TODO
    //避免书写的是偶 可能把单词拼错
    const ADD_TODO = "ADD_TODO";
    const DELETE_TODO = "DELETE_TODO";
    const YI_BU_JIA = "YI_BU_JIA";
    let store = new Vuex.Store({
        state:{
            todos:[
                {id:1,text:"土豆1号"},
                {id:2,text:"土豆2号"}
            ],
        },
        mutations:{
            [ADD_TODO]:function(state,todo){
                state.todos.push(todo);
            },
            //删除todo操作
            //payload 符合
            [DELETE_TODO]:function(state,payload){
                state.todos.splice(payload.index,1);
            }
        },
        actions:{
            [YI_BU_JIA]:function(context){
                //设置一个定时器ls 之后才触发
                setTimeout(function(){
                    //假设msg 是从后台返回
                    let msg = "土豆";
                    context.commit(ADD_TODO,{
                        text:msg,
                        id:Date.now()
                    })
                },2000)
            }
        }
    });
    let vm = new Vue({
        el:"#app",
        data:{
            inpVal:"",
        },
        store,
        methods:{
            addTodoFunc:function(){
                //当用户输入为空
                if(!this.inpVal){
                    alert("输入不能我空!!!")
                    return false;
                }
                this.$store.commit(ADD_TODO,{
                    id:Date.now(),
                    text:this.inpVal,
                });
            },
            deleteTodo:function(index){
                //对象提交风格
                this.$store.commit({
                    type:DELETE_TODO,
                    index:index
                });
            },
            addTodoAsyncFunc:function(){
                //Vuex 触发异步操作 dispatch actions
                this.$store.dispatch(YI_BU_JIA)
            }
        },
    });
</script>
</html>